package com.bandit.remoting.transport.socket;

import com.bandit.config.CustomShutdownHook;
import com.bandit.config.RpcServiceConfig;
import com.bandit.factory.SingletonFactory;
import com.bandit.provider.ServiceProvider;
import com.bandit.provider.impl.ZKServiceProviderImpl;
import com.bandit.utils.concurrent.threadpool.ThreadPoolFactoryUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

/**
 * 服务端进行服务的注册
 * @author Bandit
 * @create 2022/2/23 17:41
 */
@Slf4j
public class RpcSocketServer {
    private final ExecutorService threadPool;
    private final ServiceProvider serviceProvider;
    public static final int PORT = 9998;

    public RpcSocketServer(){
        threadPool = ThreadPoolFactoryUtils.createCustomThreadPoolIfAbsent("[socket] server-rpc-pool");
        serviceProvider = SingletonFactory.getInstance(ZKServiceProviderImpl.class);
    }

    public void registerService(RpcServiceConfig rpcServiceConfig){
        serviceProvider.publishService(rpcServiceConfig);
    }

    public void start() {
        try(ServerSocket server = new ServerSocket()) {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            server.bind(new InetSocketAddress(hostAddress,PORT));
            CustomShutdownHook.getCustomShutdownHook().clearAll();
            Socket socket = null;
            while((socket = server.accept())!=null){
                log.info("client connected [{}]", socket.getInetAddress());
                threadPool.execute(new SocketRpcRequestHandlerRunnable(socket));
            }
            threadPool.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
